﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web.Http;
using System.Web.Http.Cors;
using CVS.DAL;
using CVS.WebAPI.Mappers;
using log4net;
using Microsoft.AspNet.Identity;

namespace CVS.WebAPI.Controllers
{
    public class SubmissionsController : ApiController
    {
        private static ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        // GET api/submissions
        [Authorize]
        [System.Web.Http.HttpGet]
        public IHttpActionResult GetByTaskId(int taskId)
        {
            try
            {
                List< Submission > submissions;
                if ( User.IsInRole( "Admin" ) )
                {
                    submissions = DataRepository.GetSubmissions( taskId );
                }
                else
                {
                    submissions = DataRepository.GetSubmissions(taskId, User.Identity.Name);
                }

                return Ok( SubmissionsMapper.MapSubmissions( submissions.ToList( ) ) );
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return InternalServerError(ex);
            }
        }

        [System.Web.Http.HttpGet]
        public IHttpActionResult GetSubmissionDetails(int id)
        {
            try
            {
                return Ok(DataRepository.GetSubmissionDetails(id));
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return InternalServerError(ex);
            }
        }

        // POST api/submissions
        public void Post([FromBody] Submission submission)
        {
            try
            {
                submission.SubmittedBy = User.Identity.GetUserName( );
                DataRepository.AddSubmission(submission);
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }

        // PUT api/submissions/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/submissions/5
        public void Delete(int id)
        {
        }
    }
}
